<?php
set_time_limit(300);
defined('IN_PHPCMS') or exit('No permission resources.');
// 模型缓存路径
define('CACHE_MODEL_PATH', CACHE_PATH . 'caches_model' . DIRECTORY_SEPARATOR . 'caches_data' . DIRECTORY_SEPARATOR);
// 定义在单独操作内容的时候，同时更新相关栏目页面
define('RELATION_HTML', true);

pc_base::load_app_class('admin', 'admin', 0);
pc_base::load_sys_class('form', '', 0);
pc_base::load_app_func('util');
pc_base::load_sys_class('format', '', 0);

/**
 * 图片管理
 */
class picture extends admin
{

    private $db,$type;

    public $siteid;

    public $setting;

    public function __construct()
    {
        parent::__construct();
        $this->db = pc_base::load_model('picture_nsr_model');
        $this->type = pc_base::load_model('source_type_model');
        $this->siteid = get_siteid();
        $model_setting=pc_base::load_model('site_setting_model');
        $this->setting = $model_setting->getValue("sname_link",$this->siteid);
    }

    /**
     * 图集列表
     */
    public function index()
    {
        $status = trim($_REQUEST['status']);//图集审核标志
        $contest_id = isset($_GET['contest_id'])?$_GET['contest_id']:param::get_cookie('contest_id_3');
        $parentid = isset($_GET['catid'])?$_GET['catid']:param::get_cookie('catid_3');
        $page = $_GET['page']?(int)$_GET['page']:1;
        $num = $_GET['num']?(int)$_GET['num']:10;
        $select_categorys = $this->type->getSource(3,$parentid);
        $contest_model = pc_base::load_model('contest_model');
        $categorys = $contest_model->now_contest_select($contest_id);
        $cookie_time = SYS_TIME+120;

        //获取管理员真实姓名数据
        $admin_model = pc_base::load_model('admin_model');
        $adminInfo = $admin_model->getRealnameInfo();
        //资讯审核管理开启，查询status为0的资讯：即为自动采集过来的资讯需要认为审核、编辑
        if($status=='unchecked'){
            $sql="select p.*,c.contest_id from nsrweb_picture_nsr as p LEFT JOIN nsrweb_contest_source as c on p.id = c.source_id where p.status=0";
        }else{
            $sql="select p.*,c.contest_id from nsrweb_picture_nsr as p LEFT JOIN nsrweb_contest_source as c on p.id = c.source_id where p.status=1";
        }
        $sql .= " and p.siteid =" . $this->siteid;
        if (isset($_GET['title']) && !empty($_GET['title'])) {
            $title = trim($_GET['title']);
            $sql .= " and p.`title` like '%$title%' ";
        }
        if ($parentid) {
            param::set_cookie('catid_3',$parentid,$cookie_time);
            $sql .= " and p.type_id = " . $parentid;
        } else {
            param::set_cookie('catid_3','');
        }
        if ($contest_id) {
            param::set_cookie('contest_id_3',$contest_id,$cookie_time);
            $sql .= " and c.contest_id = " . $contest_id;
        } else {
            param::set_cookie('contest_id_3','');
        }
        if (isset($_GET['image_square']) && !empty($_GET['image_square'])) {
            $image_square = trim($_GET['image_square']);
            if ($image_square == 1) {
                $sql .= " and p.image_square1 != '' and p.image_square2 != '' and p.image_square3 != ''";
            } else {
                $sql .= " and (p.image_square1 = '' or  p.image_square2 = '' or p.image_square3 = '')";
            }
        }
        $sql .= " group by p.id order by p.id desc ";//echo $sql;die;
        $picture_list = $this->db->my_listinfos($sql, $page, $num);
        foreach ($picture_list as $k => $v) {
            $contestInfo = $contest_model->get_one(array('id'=>$v['contest_id']));
            $typeInfo = $this->type->get_one(array('id'=>$v['type_id']));
            $picture_list[$k]['contestName'] = $contestInfo['name'];
            $picture_list[$k]['typeName'] = $typeInfo['cn_name'];
            $pictureurls = json_decode($v['pictureurls'],true);
            $picture_list[$k]['pics'] = count($pictureurls);
        }
        $pages = $this->db->pages;
        include $this->admin_tpl('picture_list');
    }

    /**
     * 图集-组图-alt字段里面如果有中文则保留；否则把alt设置为空
     */
    public function deal_data()
    {
        //获取图集中所有的id、pictureurls
        $picture_list = $this->db->select(' id>=21 and siteid=1 and status=1','id,pictureurls');
        //循环处理单个图集中的 pictureurls
        foreach ($picture_list as $k => $v) {
            $pictureurls_new = array();#设置一个空数组备用
            $pictureurls = json_decode($v['pictureurls'],true);
            foreach ($pictureurls as $key=>$value){
                $str = $value['alt'];
                if (preg_match("/[\x7f-\xff]/", $str)) {  //判断字符串中是否有中文
                    $pictureurls_new[$key] = $value;
                } else {
                    $value['alt'] = '';
                    $pictureurls_new[$key] = $value;
                }
            }
            //json_encode 正斜杠、中文不转义！！！
            $pictureurls_new = json_encode($pictureurls_new,JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
            $result = $this->db->update(array('pictureurls'=>$pictureurls_new), array('id'=>$v['id']));
            //echo "<pre>";print_r($pictureurls_new);die;
        }
        echo "<script>alert('成功！');</script>";
    }

    /**
     * 添加图集
     */
    public function add()
    {
        if (isset($_POST['dosubmit']) && ! empty($_POST['dosubmit']) || isset($_POST['dosubmit1']) && ! empty($_POST['dosubmit1'])) {
            $titlepd = $this->public_check_picture($_POST['picture']['title']);
            if (!$titlepd) {
                showmessage(L('title-exist'), HTTP_REFERER);
            }
            $picture = $this->db->check($_POST['picture']);
            $id = $this->db->edit($picture);
            if ($id) {
                $contest_source_model = pc_base::load_model('contest_source_model');
                if ($_POST['contestid']) {
                    $contest_source_model->edit($id, $_POST['contestid'], 3);
                }
                $data = array();
                $cateList = array_unique($_POST['othor_catid']);
                foreach ($cateList as $k => $v) {
                    $data[$k]['cate_id']=$v;
                    $data[$k]['source_id']=$id;
                    $data[$k]['source_type']=3;
                    $data[$k]['created_by'] =  $_SESSION['userid'];
                    $data[$k]['updated_by'] =  $_SESSION['userid'];

                    $data[$k]['create_time'] = date("Y-m-d H:i:s",time());
                    $data[$k]['update_time'] = date("Y-m-d H:i:s",time());
                }
                $category_source_model = pc_base::load_model('category_source_model');
                if(!empty($data)){
                    $res=$category_source_model->multiInsert($data);
                }
                $cookie_time = SYS_TIME+120;
                param::set_cookie('catid_3',$picture['type_id'],$cookie_time);
                param::set_cookie('contest_id_3',$_POST['contestid'],$cookie_time);

                //记录行为日志
                $log_content = '<span style="color:green;">添加图集</span>[新生成图集id：'.$id.'；图集标题：'.$picture['title'].']';
                $this->manage_admin_log($log_content);

                if ($_POST['dosubmit1']) {
                    showmessage(L('add_picture_success'), HTTP_REFERER);
                } else {
                    showmessage(L('add_picture_success'), '?m=picture&c=picture&a=index');
                }
            } else {
                showmessage(L('add_picture_error'), HTTP_REFERER);
            }
        } else {
            $contest_model = pc_base::load_model('contest_model');
            $contest_id = param::get_cookie('contest_id_3');
            $parentid = param::get_cookie('catid_3');
            $show_validator = $show_scroll = true;
            pc_base::load_sys_class('form', '', 0);
            $categorys = $contest_model->now_contest_select($contest_id);
            $types = $this->type->getSource(3, $parentid);
            pc_base::load_app_func('global', 'admin');
            include $this->admin_tpl('picture_add');
        }
    }

    /**
     * 图集修改
     */
    public function edit()
    {
        $category_source_model = pc_base::load_model('category_source_model');
        if (! isset($_GET['id']) || empty($_GET['id'])) {
            showmessage(L('illegal_action'), HTTP_REFERER);
        }
        $id = intval($_GET['id']);
        if (isset($_POST['dosubmit']) && ! empty($_POST['dosubmit'])) {
            $status = trim($_REQUEST['status']);
            $titlepd = $this->public_check_picture($_POST['picture']['title']);
            if (!$titlepd) {
                showmessage(L('title-exist'), HTTP_REFERER);
            }
            $picture = $this->db->check($_POST['picture'], 'edit');
            $ids = $this->db->edit($picture, $id);
            if ($ids) {
                $contest_source_model = pc_base::load_model('contest_source_model');
                $contest_source_model->delete(array('source_id'=>$id,'source_type'=>3));
                if ($_POST['contestid']) {
                    $contest_source_model->edit($id, $_POST['contestid'], 3);
                }
                //如果页面端清空已绑定的栏目，则$_POST['othor_catid']为空，删除所有已绑定的栏目
                $data = array();
                if($_POST['othor_catid']){
                    $cateList = array_unique($_POST['othor_catid']);
                    foreach ($cateList as $k => $v) {
                        //先删除已绑定的栏目资讯，以最新提交的为准，吴发顶，2017-08-02 15:25:28
                        $del_flag = $category_source_model->delete(array('source_type'=>3,'source_id'=>$id));
                        $data[$k]['cate_id']=$v;
                        $data[$k]['source_id']=$id;
                        $data[$k]['source_type']=3;
                        $data[$k]['created_by'] =  $_SESSION['userid'];
                        $data[$k]['updated_by'] =  $_SESSION['userid'];
    
                        $data[$k]['create_time'] = date("Y-m-d H:i:s",time());
                        $data[$k]['update_time'] = date("Y-m-d H:i:s",time());
                    }
                    if(!empty($data)){
                        $res=$category_source_model->multiInsert($data);
                    }
                }else{
                    $del_flag = $category_source_model->delete(array('source_type'=>3,'source_id'=>$id));
                }
                //更新发布时间到关联表
                $update_time = $picture['publish_time']?$picture['publish_time']:$picture['update_time'];
                $category_source_model->update(array('update_time'=>$update_time), array('source_type'=>3,'source_id'=>$id));

                //记录行为日志
                $log_content = '<span style="color:blue;">修改图集</span>[图集id：'.$id.'；图集标题：'.$picture['title'].']';
                $this->manage_admin_log($log_content);
                //判断是否是图集审核列表过来的
                if($status=='unchecked'){
                    showmessage(L('edit_picture_success'), '?m=picture&c=picture&a=index&status=unchecked');
                }else{
                    showmessage(L('edit_picture_success'), '?m=picture&c=picture&a=index');
                }
            } else {
                showmessage(L('edit_picture_error'), HTTP_REFERER);
            }
        } else {           
            $show_dialog = $show_validator = true;
            $info = $this->db->get_one(array('id'=>$id, 'siteid'=>$this->siteid));
            extract($info);
            $status = trim($_REQUEST['status']);
            //组图反序列化
            $pictureurls = json_decode($pictureurls);//var_dump($pictureurls);die;
            $parentid = $type_id?$type_id:param::get_cookie('catid_3');
            //取图集类型
            $types = $this->type->getSource(3, $parentid);
            $contest_source_model = pc_base::load_model('contest_source_model');
            $contest_model = pc_base::load_model('contest_model');
            $csInfo = $contest_source_model->get_one(array('source_id'=>$id));
            $contest_id = $csInfo['contest_id']?$csInfo['contest_id']:param::get_cookie('contest_id_3');
            //取正在进行赛事
            $categorys = $contest_model->now_contest_select($contest_id);
            //取绑定栏目信息
            $category_model = pc_base::load_model('category_model');
            $cateList = $category_source_model->select(array('source_id'=>$id,'source_type'=>3),'cate_id');
            $cates = '';
            foreach ($cateList as $k=>$v) {
                $cateInfo = $category_model->get_one(array('catid'=>$v['cate_id']),'catid,catname');
                $cates .= '<li id="v'.$cateInfo['catid'].'">·<input type="hidden" name="othor_catid[]" value="'.$cateInfo['catid'].'"><span>'.$cateInfo['catname'].'</span><a href="javascript:;" class="close" onclick="remove_id('."'v".$cateInfo['catid']."'".')"></a></li>';
            }

            //获取站点模板信息
            pc_base::load_app_func('global', 'admin');
            include $this->admin_tpl('picture_edit');
        }
    }

    /**
     * 图集删除
     */
    public function delete()
    {
        if (! isset($_GET['id']) || empty($_GET['id'])) {
            showmessage(L('illegal_parameters'), HTTP_REFERER);
        } else {
            $id = intval($_GET['id']);
            $title = trim($_GET['title']);
            if ($id < 1)
                return false;
            $result = $this->db->edit(array('status'=>2), $id);

            //记录行为日志
            $log_content = '<span style="color:red;">删除图集</span>[图集id：'.$id.'；图集标题：'.$title.']';
            $this->manage_admin_log($log_content);

            if ($result) {
                //删除绑定关系
                $this->deleteBind($id, 3);
                showmessage(L('operation_success'), HTTP_REFERER);
            } else {
                showmessage(L("operation_failure"), HTTP_REFERER);
            }
        }
    }
    

    /**
     * 图集审核通过
     * time：2017-10-25 10:52:18
     * author：angel_in_us
     */
    public function check_in()
    {
        if (! isset($_GET['id']) || empty($_GET['id'])) {
            showmessage(L('illegal_parameters'), HTTP_REFERER);
        } else {
            $id = intval($_GET['id']);
            if ($id < 1)
                return false;
            $title = $_GET['title']?$_GET['title']:'暂无该图集标题数据，请联系管理员！';
            $result = $this->db->edit(array('status'=>1,'update_time'=>date("Y-m-d H:i:s",time()),'updated_by'=>$_SESSION['userid']), $id);
            //记录行为日志
            $log_content = '<span style="color:#FF9933;">图集审核通过</span>[图集id：'.$id.'；图集标题：'.$title.']';
            //echo $log_content;die;
            $this->manage_admin_log($log_content);

            if ($result) {
                showmessage(L('operation_success'), HTTP_REFERER);
            } else {
                showmessage(L("operation_failure"), HTTP_REFERER);
            }
        }
    }

    /**
     * 图集批量删除
     */
    public function deleteAll ()
    {
        if(isset($_GET['dosubmit'])) {
            foreach($_POST['ids'] as $id) {
                $this->db->edit(array('status'=>2),$id);
                //删除绑定关系
                $this->deleteBind($id, 3);
            }

            //记录行为日志
            $id = implode(',',$_POST['ids']);
            $log_content = '<span style="color:red;">批量删除图集</span>[图集id：('.$id.')]';
            $this->manage_admin_log($log_content);

            showmessage(L('operation_success'), HTTP_REFERER);
        } else {
            showmessage(L('operation_failure'), HTTP_REFERER);
        }
    }

    /**
     * 检验标题否存在，避免标题重复
     */
    public function public_check_picture ($title)
    {
        $type = intval($_GET['type']);
        if ($type == 1) {
            $r = $this->db->get_one(array('siteid' => $this->siteid, 'title' => addslashes($_GET['title']), 'status'=>1), 'id');
            if($r['id']) {
                echo 0;die;
            } else {
                echo 1;die;
            }
        } else {
            if(!$title) showmessage(L('no-title'), HTTP_REFERER);;
            if(pc_base::load_config('system', 'charset')=='gbk') {
                $title = safe_replace(iconv('UTF-8', 'GBK', $title));
            }
            $title = addslashes($title);
            if($_GET['id']) {
                $id = intval($_GET['id']);
                $r = $this->db->get_one(array('id'=>$id, 'siteid' => $this->siteid));
                if($r['title'] == $title) {
                    return true;
                }
            }
            $r = $this->db->get_one(array('siteid' => $this->siteid, 'title' => $title, 'status'=>1), 'id');
            if($r['id']) {
                return false;
            } else {
                return true;
            }
        }
    }

    /**
     * 绑定列表
     */
    public function show ()
    {
        if (!isset($_GET['id']) || empty($_GET['id'])) {
            showmessage(L('illegal_action'), HTTP_REFERER);
        }
        $id = intval($_GET['id']);
        $source_type = intval($_GET['source_type']);

        $info = $this->db->get_one(array('id'=>$id, 'siteid'=>$this->siteid));
        $types = $this->type->get_one(array('id'=>$info['type_id']));

        include $this->admin_tpl('picture_show');
    }

    /**
     * 删除绑定关系
     */
    public function deleteBind ($id, $source_type) {

        $category_source_model = pc_base::load_model('category_source_model');
        $contest_source_model = pc_base::load_model('contest_source_model');
        $talent_source_model = pc_base::load_model('talent_source_model');
        $goods_source_model = pc_base::load_model('goods_source_model');
        $activity_source_model = pc_base::load_model('activity_source_model');
        
        //执行删除操作
        $category_source_model->deleteBind($id, $source_type);
        $contest_source_model->deleteBind($id, $source_type);
        $talent_source_model->deleteBind($id, $source_type);
        $goods_source_model->deleteBind($id, $source_type);
        $activity_source_model->delete(array('source_id'=>$id,'source_type'=>$source_type));
    }

    /**
     * 获取来源链接
     */
    public function ajaxSourceLink (){
        $id = $_POST['id']?intval($_POST['id']):'';
        if ($id) {
            $is_publish = $_POST['is_publish'] == 1?0:1;
            $info = $this->db->get_one(array('id'=>$id));
            $res = $this->db->edit(array('is_publish'=>$is_publish), $id);
            //记录行为日志
            $log_content = ($is_publish==1?'<span style="color:green;">图集发布</span>':'<span style="color:red;">图集取消发布</span>').'[图集id：'.$id.'；图集标题：'.$info['title'].']';
            $this->manage_admin_log($log_content);

            if ($res) {
                echo 1;die;
            } else {
                echo 0;die;
            }
        } else {
            $source_name = $_GET['source_name']?trim($_GET['source_name']):'';
            $data = $this->setting;
            $res = array();
            $res['status'] = 0;
            $res['source_link'] = '';
            foreach ($data as $v) {
                if ($v['source_name'] == $source_name) {
                    $res['status'] = 1;
                    $res['source_link'] = $v['source_link'];
                    echo json_encode($res);die;
                }
            }
            echo json_encode($res);die;
        }
    }
}